//
//  aaViewController.m
//  mySwift
//
//  Created by X-MEN on 2021/12/7.
//


#import "OCViewController.h"
#import "XMDemoTableViewCell.h"
#import "UIimageTableViewCell.h"
#import "MaxLabelTableViewCell.h"
#import "LabelPriorityTableViewCell.h"
#import "LabelTempPriorityTableViewCell.h"
#import "CollectionTableViewCell.h"
#import "TagTableViewCell.h"
#import "PictureTableViewCell.h"
#import "BBPopupMenuCoverView.h"
#import "XMenSwift-Swift.h"
#import "TempTableViewCell.h"
#import <FMDB/FMDB.h>

@interface OCViewController ()
/** <#名字#> */
@property (nonatomic ,strong) NSMutableArray *imageArray;
@property (nonatomic, strong) BBPopupMenuCoverView *coverView;
@property (nonatomic, strong) NSString *dbPath;
@end

@implementation OCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUi];
//    [self MJBeginRefreshing];
//    UIImage *adImg = [UIImage imageNamed:@"icon_nav_add"];
//    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    addBtn.frame = CGRectMake(0, 0, 44, 44);
//    [addBtn setImage:adImg forState:UIControlStateNormal];
//    [addBtn addTarget:self action:@selector(showMenuViewAction) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
//    self.navigationItem.rightBarButtonItem = btnItem;
    
    //1.创建database路径
        NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *dbPath = [docuPath stringByAppendingPathComponent:@"test.db"];
       _dbPath = dbPath;
        NSLog(@"!!!dbPath = %@",dbPath);
         //2.创建对应路径下数据库
       FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
        //3.在数据库中进行增删改查操作时，需要判断数据库是否open，如果open失败，可能是权限或者资源不足，数据库操作完成通常使用close关闭数据库
        [db open];
        if (![db open]) {
            NSLog(@"db open fail");
            return;
        }
        //4.数据库中创建表（可创建多张）
        NSString *sql = @"create table if not exists t_student ('ID' INTEGER PRIMARY KEY AUTOINCREMENT,'name' TEXT NOT NULL, 'phone' TEXT NOT NULL,'score' INTEGER NOT NULL)";
        //5.执行更新操作 此处database直接操作，不考虑多线程问题，多线程问题，用FMDatabaseQueue 每次数据库操作之后都会返回bool数值，YES，表示success，NO，表示fail,可以通过 @see lastError @see lastErrorCode @see lastErrorMessage
        BOOL result = [db executeUpdate:sql];
        if (result) {
            NSLog(@"create table success");
            
        }
//        [db close];
    
    /**
     增删改查中 除了查询（executeQuery），其余操作都用（executeUpdate）
     //1.sql语句中跟columnname 绑定的value 用 ？表示，不加‘’，可选参数是对象类型如：NSString，不是基本数据结构类型如：int，方法自动匹配对象类型
     - (BOOL)executeUpdate:(NSString*)sql, ...;
     //2.sql语句中跟columnname 绑定的value 用%@／%d表示，不加‘’
     - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
     //3.sql语句中跟columnname 绑定的value 用 ？表示的地方依次用 (NSArray *)arguments 对应的数据替代
     - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
     //4.同3 ，区别在于多一个error指针，记录更新失败
     - (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
     //5.同3，区别在于用 ？ 表示的地方依次用(NSDictionary *)arguments中对应的数据替代
     - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
     - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
     */
    //0.直接sql语句
    //    BOOL result = [db executeUpdate:@"insert into 't_student' (ID,name,phone,score) values(110,'x1','11',83)"];
        //1.
    //    BOOL result = [db executeUpdate:@"insert into 't_student'(ID,name,phone,score) values(?,?,?,?)",@111,@"x2",@"12",@23];
        //2.
    //    BOOL result = [db executeUpdateWithFormat:@"insert into 't_student' (ID,name,phone,score) values(%d,%@,%@,%d)",112,@"x3",@"13",43];
        //3.
    
  

    
    BOOL result1 = [db executeUpdate:@"insert into 't_student'(ID,name,phone,score) values(?,?,?,?)" withArgumentsInArray:@[@113,@"x3",@"13",@53]];
        if (result) {
            NSLog(@"insert into 't_studet' success");

        } else {

        }
    
    FMResultSet *result2 = [db executeQuery:@"select * from 't_student' where ID = ?" withArgumentsInArray:@[@113]];
    NSMutableArray *arr = [NSMutableArray array];
      while ([result2 next]) {
//          PersonVO *person = [PersonVO new];
//          person.ID = [result2 intForColumn:@"ID"];
//          person.name = [result2 stringForColumn:@"name"];
//          person.phone = [result2 stringForColumn:@"phone"];
//          person.score = [result2 intForColumn:@"score"];
//          [arr addObject:person];
          NSLog(@"从数据库查询到的人员 %@",[result2 stringForColumn:@"name"]);
          
      }
    [db close];

}

-(NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

#pragma mark - 初始化Ui

-(void)setupUi {
    self.navigationItem.title = @"OC列表各种样式";
    [self configTableView];
  
}

- (void)configTableView {
    [self setupTableViewWithStyle:UITableViewStylePlain];
//        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {;
//            make.top.mas_equalTo(self.view).offset(kTopHeight);
//            make.bottom.equalTo(self.view).offset(-kBottomSafeHeight);
//            make.trailing.equalTo(self.view).offset(0);
//            make.leading.equalTo(self.view).offset(0);
//        }];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TempTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([TempTableViewCell class])];
    
    [self.tableView registerClass:[XMDemoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XMDemoTableViewCell class])];
    
    [self.tableView registerClass:[UIimageTableViewCell class] forCellReuseIdentifier:NSStringFromClass([UIimageTableViewCell class])];
    
    [self.tableView registerClass:[MaxLabelTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MaxLabelTableViewCell class])];
    
    //优先级
    [self.tableView registerClass:[LabelPriorityTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LabelPriorityTableViewCell class])];
    
    [self.tableView registerClass:[LabelTempPriorityTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LabelTempPriorityTableViewCell class])];
    
    [self.tableView registerClass:[CollectionTableViewCell class] forCellReuseIdentifier:NSStringFromClass([CollectionTableViewCell class])];
    
    [self.tableView registerClass:[TagTableViewCell class] forCellReuseIdentifier:NSStringFromClass([TagTableViewCell class])];
    
    [self.tableView registerClass:[PictureTableViewCell class] forCellReuseIdentifier:NSStringFromClass([PictureTableViewCell class])];
    
    
    

}


#pragma mark - 事件处理

- (void)showMenuViewAction:(CGPoint)point {
    __weak __typeof(self)weakSelf = self;

    if (self.coverView == nil) {
        self.coverView = [[BBPopupMenuCoverView alloc] initWithFrame:self.view.bounds];
        self.coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        self.coverView.touchEventBlock = ^{
            weakSelf.coverView = nil;
        };
        [self.view addSubview:self.coverView];
        //60按钮的宽
        CGFloat menuViewW = 160;
        BBPopupMenuView *menuView = [[BBPopupMenuView alloc] initWithFrame:CGRectMake(point.x - menuViewW + 60, point.y + 30, menuViewW, 180)];
        menuView.bgImageView.image = [UIImage imageNamed:@"pop_bg"];
        menuView.menuItems = @[[[BBPopupMenuItem alloc] initWithTitle:@"扫描需求" image:[UIImage imageNamed:@"icon_scan"]], [[BBPopupMenuItem alloc] initWithTitle:@"我的匹配" image:[UIImage imageNamed:@"icon_match"]]];
        menuView.alpha = 1.0;
//        [UIView animateWithDuration:0.25 animations:^{
//            menuView.alpha = 1.0;
//        }];
        [menuView setTarget:self action:@selector(menuViewDidClick:)];
        [self.coverView addSubview:menuView];
    } else {
        [self menuViewDidClick:nil];
    }
}

- (void)menuViewDidClick:(UIButton *)btn {
    [self.coverView removeFromSuperview];
    self.coverView = nil;
    
}


#pragma mark - UITableViewDataSource UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 15;
    return self.dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        UIimageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UIimageTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.row == 1) {
        MaxLabelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MaxLabelTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    if (indexPath.row == 2) {
        LabelPriorityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LabelPriorityTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
    if (indexPath.row == 3) {
        LabelTempPriorityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LabelTempPriorityTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
    if (indexPath.row == 4) {
        CollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CollectionTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = @[@"",@"",@"",@"",@""];
        cell.collectionReloadHightBlock = ^{
            [tableView reloadData];
        };
        return cell;
        
    }
    
    if (indexPath.row == 5) {
        TagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TagTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = @[@"标签",@"我是标签",@"yellow",@"tag",@"看看老铁的标签",@"这是个很长的标签看看一行",@"超级长的标签超超级的这是个很长的标签看看一行超级长的标签超超级的这是个"];
        cell.collectionReloadHightBlock = ^{
            [tableView reloadData];
        };
        return cell;

    }
    
    if (indexPath.row == 6) {
        PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PictureTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.vc = self;
        cell.dataArray = self.imageArray;
        cell.collectionReloadHightBlock = ^{
            [tableView reloadData];
        };
        return cell;

    }
    
    if (indexPath.row == 7) {
        __weak __typeof(self)weakSelf = self;
        TempTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TempTableViewCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.btnEventBlcok = ^(UIButton * _Nonnull sender) {
            UIWindow * window= [[[UIApplication sharedApplication] delegate] window];
            CGRect rect = [sender convertRect:sender.bounds toView:window];
            NSLog(@"x是%f ,y是%f",rect.origin.x,rect.origin.y);
            [weakSelf showMenuViewAction:rect.origin];
        };
        return cell;

    }
    
    XMDemoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XMDemoTableViewCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        return 140;
    }
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 告诉tableView所有cell的估算高度
    self.tableView.estimatedRowHeight = 100;
    return self.tableView.rowHeight;;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}


@end
